#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <thread>
#include <unordered_map>
#include <functional>
#include <cstring>
#include <cerrno>
#include <cstdlib>
#include "loop_queue.hpp"
#include "../easysock.hpp"
#include "err.hpp"

namespace udp
{
class udp_server : public inet::udp::server
{
using func_t = std::function<std::string(std::string)>;

public:
    udp_server(func_t cb, uint16_t port) 
        : server(port), _service(cb)
    {}

    ~udp_server()
    {
    }

    void init_server()
    {
    }

    void start()
    {
        while (true)
        {
            std::string msg;
            std::string peer_ip;
            uint16_t peer_port;

            ssize_t s = recvfrom(&msg, 1024, &peer_ip, &peer_port);
            if (s <= 0) continue;
            
            std::string name = peer_ip + ":" + std::to_string(peer_port);

            std::cout << "cast message to user " << name << std::endl;
            std::string rsp = '[' + name + "] " + msg;
            sendto(rsp, peer_ip, peer_port);
        }
    }

private:
    func_t _service;
};

}

